package com.jxltech.unicam.utils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;

public class ResizableSplitPane extends JSplitPane {

        //
        // instance variables
        //

        private boolean painted;

        private double defaultDividerLocation;

        private ResizableSplitPane resizableSplitPane = this;

        private double currentDividerLocation;

        private Component first;

        private Component second;

        private boolean dividerPositionCaptured = false;

        //
        // constructors
        //

        public ResizableSplitPane(int splitType, Component first, Component second, Component parent) {
            this(splitType, first, second, parent, 0.5);
        }

        public ResizableSplitPane(int splitType, Component first, Component second, Component parent, double defaultDividerLocation) {
            super(splitType, first, second);
            this.defaultDividerLocation = defaultDividerLocation;
            this.currentDividerLocation = defaultDividerLocation;
            this.setResizeWeight(defaultDividerLocation);
            this.first = first;
            this.second = second;
            parent.addComponentListener(new DividerLocator());
            first.addComponentListener(new DividerMovedByUserComponentAdapter());
        }

        //
        // trivial getters and setters
        //

        public double getDefaultDividerLocation() {
            return defaultDividerLocation;
        }

        public void setDefaultDividerLocation(double defaultDividerLocation) {
            this.defaultDividerLocation = defaultDividerLocation;
        }

        //
        // implementation
        //

        @Override
        public void paint(Graphics g) {
            super.paint(g);
            if (!painted) {
                painted = true;
                this.setDividerLocation(currentDividerLocation);
            }
            dividerPositionCaptured = false;
        }

        private class DividerLocator extends ComponentAdapter {
            @Override
            public void componentResized(ComponentEvent e) {
                setDividerLocation(currentDividerLocation);
            }
        }

        private class DividerMovedByUserComponentAdapter extends ComponentAdapter {
            @Override
            public void componentResized(ComponentEvent e) {
                if (dividerPositionCaptured == false) {
                    dividerPositionCaptured = true;
                    currentDividerLocation = (double) first.getWidth() / (double) (first.getWidth() + second.getWidth());
                    System.out.println(currentDividerLocation);
                }
            }
        }

    }

